<template>
  <div class="Detail">
    <div class="mixin">
      <div class="left">
        <LeftSideTheme @filter-change="handleFilterChange"></LeftSideTheme>
      </div>
      <div class="right">
        <div class="search-info">
          <div class="search-header">
            <div class="search-result-count">
              共<span class="count-number">{{ totalCount }}</span>条结果
            </div>
            <div class="search-controls">
              <div class="pagination-controls">
                <i
                  class="iconfont icon-icon-zuoyouqiehuan-zuo"
                  @click="handlePrevPage"
                  :class="{ disabled: currentPage === 1 }"
                ></i>
                <div class="page-info">{{ currentPage }}/{{ totalPages }}</div>
                <i
                  class="iconfont icon-icon-zuoyouqiehuan-you"
                  @click="handleNextPage"
                  :class="{ disabled: currentPage === totalPages }"
                ></i>
              </div>
              <div class="view-controls">
                <div
                  class="fenye"
                  @click="handleChangeViewMode('fenye')"
                  :class="{ active: viewMode === 'fenye' }"
                >
                  <i class="iconfont icon-fenye"></i>
                </div>
                <div
                  class="chanpinliebiaopubuliumoshi"
                  @click="handleChangeViewMode('chanpinliebiaopubuliumoshi')"
                  :class="{ active: viewMode === 'chanpinliebiaopubuliumoshi' }"
                >
                  <i class="iconfont icon-chanpinliebiaopubuliumoshi"></i>
                </div>
              </div>
            </div>
          </div>

          <div class="search-result-area">
            <div class="operation-bar">
              <div class="left-operations">
                <el-checkbox
                  class="selected-checkbox"
                  :value="isAllCurrentPageSelected"
                  @change="handleSelectAll"
                >
                  全选本页
                </el-checkbox>
                <div class="selected-count">
                  已选：<span>{{ selectedCount }}/{{ totalCount }}条</span>
                </div>
                <el-button
                  type="text"
                  class="qing"
                  @click="handleClearSelection"
                >
                  清除
                </el-button>
              </div>
              <div class="right-operations">
                <div @click="handleSort('relevance')">
                  相关度
                  <i
                    class="iconfont icon-shengxujiangxu"
                    :class="{ active: sortType === 'relevance' }"
                  ></i>
                </div>
                <div @click="handleSort('time')">
                  时间
                  <i
                    class="iconfont icon-shengxujiangxu"
                    :class="{ active: sortType === 'time' }"
                  ></i>
                </div>
                <div @click="handleDownload">
                  下载<i class="iconfont icon-xiazai"></i>
                </div>
                <div @click="handleExport">
                  导出<i class="iconfont icon-daochu2"></i>
                </div>
                <div @click="handleStatistic">
                  统计分析<i class="iconfont icon-tubiao"></i>
                </div>
                <div class="button1" @click="handleTranslate">
                  <i class="iconfont icon-zhongyingwen"></i>翻译
                </div>
              </div>
            </div>

            <div class="search-in-result">
              <div class="search-in-result__label">在结果中搜索</div>
              <div class="search-in-result__input">
                <el-input
                  v-model="searchInResultKeyword"
                  placeholder="请输入内容"
                  @keyup.enter="handleSearchInResult"
                ></el-input>
              </div>
              <div class="search-in-result__button">
                <el-button type="primary" @click="handleSearchInResult"
                  >确定</el-button
                >
              </div>
            </div>
          </div>

          <!-- 搜索结果列表 -->
          <div class="result-list-container">
            <!-- 列表视图 -->
            <result-list
              :items="searchResults"
              :selected-ids="selectedIds"
              :sort-type="sortType"
              @select="handleSelectItem"
            />

        

            <!-- 加载状态提示 -->
            <div class="loading-tip" v-if="isLoading && viewMode === 'chanpinliebiaopubuliumoshi'">
              加载中...
            </div>
            <div class="no-more-tip" v-if="!hasMore && viewMode === 'chanpinliebiaopubuliumoshi'">
              没有更多数据了
            </div>

            <!-- 空状态 -->
            <div class="empty-state" v-if="searchResults.length === 0 && !isLoading">
              <div class="aa">
                <img src="../assets/img/wu.png" alt="空状态" />
                <div class="empty-text">暂无数据</div>
              </div>
            </div>
          </div>

          <!-- 分页组件只在分页模式下显示 -->
          <div class="pagination" v-if="viewMode === 'fenye' && searchResults.length > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="pageSize"
              layout="prev, pager, next, jumper"
              :total="totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <export-dialog ref="exportDialog"></export-dialog>
  </div>
</template>

<script>
import LeftSideTheme from "../components/SearchPage/LeftSideTheme.vue";
import ResultList from "../components/SearchPage/ResultList.vue";
import ExportDialog from "../components/SearchPage/ExportDialog.vue";

export default {
  components: {
    LeftSideTheme,
    ResultList,
    ExportDialog,
  },
  data() {
    return {
      SELECT_LIMIT: 500, // 系统勾选上限500条
      currentPage: 1,
      totalCount: 0,
      pageSize: 10, // 统一的每页条数，顶部/底部分页共用
      viewMode: "fenye", // fenye:列表视图, chanpinliebiaopubuliumoshi:瀑布流视图
      searchResults: [], // 存储搜索结果列表
      allResults: [], // 瀑布流模式下存储所有加载的数据
      selectedIds: [], // 存储选中的结果ID
      sortType: "relevance", // 排序类型：relevance-相关度；time-时间
      sortOrder: "desc", // 排序方向：asc-升序；desc-降序
      searchInResultKeyword: "",
      filters: {}, // 筛选条件
      isLoading: false, // 加载状态
      hasMore: true, // 是否还有更多数据
    };
  },
  computed: {
    totalPages() {
      if (this.totalCount === 0) return 1;
      return Math.ceil(this.totalCount / this.pageSize);
    },
    selectedCount() {
      return this.selectedIds.length;
    },
    isAllCurrentPageSelected() {
      if (this.searchResults.length === 0) return false;
      return this.searchResults.every((item) =>
        this.selectedIds.includes(item.id)
      );
    },
  },
  methods: {
    // 滚动处理
    handleScroll() {
      // 只在瀑布流模式下执行
      if (this.viewMode !== "chanpinliebiaopubuliumoshi" || !this.hasMore || this.isLoading) return;

      const container = document.querySelector(".home");
      if (!container) return;

      const { scrollTop, scrollHeight, clientHeight } = container;
      // 当滚动到底部50px范围内时触发加载
      if (scrollTop + clientHeight >= scrollHeight - 50) {
        this.fetchData(true);
      }
    },

    // 视图模式切换
    handleChangeViewMode(mode) {
      if (this.viewMode === mode) return;
      
      this.viewMode = mode;
      this.currentPage = 1;
      this.allResults = [];
      this.hasMore = true;
      this.selectedIds = [];
      this.fetchData();
    },

    // 获取数据
    async fetchData(isLoadMore = false) {
      if (this.isLoading) return;
      
      try {
        this.isLoading = true;
        const params = {
          page: isLoadMore ? this.currentPage + 1 : 1,
          pageSize: this.pageSize,
          sortType: this.sortType,
          sortOrder: this.sortOrder,
          ...this.filters,
          keyword: this.searchInResultKeyword,
        };

        // 模拟API请求
        const response = await this.mockApi(params);
        
        if (this.viewMode === "chanpinliebiaopubuliumoshi") {
          // 瀑布流模式：累积数据
          if (isLoadMore) {
            this.allResults = [...this.allResults, ...response.data];
            this.currentPage++;
          } else {
            this.allResults = response.data;
            this.currentPage = 1;
          }
          this.searchResults = this.allResults;
          this.hasMore = response.data.length === this.pageSize;
        } else {
          // 分页模式：替换数据
          this.searchResults = response.data;
          this.totalCount = response.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.searchResults = [];
        this.totalCount = 0;
      } finally {
        this.isLoading = false;
      }
    },

    // 模拟API请求
    mockApi(params) {
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockResults = Array.from({ length: params.pageSize }, (_, i) => {
            const id = (params.page - 1) * params.pageSize + i + 1;
            return {
              id,
              title: `搜索结果标题 ${id}`,
              content: `这是搜索结果${id}的详细描述内容...`,
              source: `来源${Math.floor(Math.random() * 5) + 1}`,
              time: `202${Math.floor(Math.random() * 4) + 1}-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
            };
          });

          resolve({
            data: mockResults,
            total: Math.floor(Math.random() * 100) + 100
          });
        }, 300);
      });
    },

    // 底部分页：切换每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },

    // 底部分页：切换当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectedIds = [];
      this.fetchData();
    },

    // 处理筛选条件变化
    handleFilterChange(filters) {
      this.filters = filters;
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },

    // 顶部分页：上一页
    handlePrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.selectedIds = [];
        this.fetchData();
      }
    },

    // 顶部分页：下一页
    handleNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.selectedIds = [];
        this.fetchData();
      }
    },

    // 选择控制
    handleSelectAll(val) {
      if (val) {
        const currentUnselectedIds = this.searchResults
          .map((item) => item.id)
          .filter((id) => !this.selectedIds.includes(id));
        if (currentUnselectedIds.length === 0) return;

        const remainingLimit = this.SELECT_LIMIT - this.selectedIds.length;
        if (remainingLimit <= 0) {
          this.$message.warning(
            `系统勾选上限为${this.SELECT_LIMIT}条，已达上限`
          );
          return;
        }

        const idsToAdd = currentUnselectedIds.slice(0, remainingLimit);
        this.selectedIds = [...new Set([...this.selectedIds, ...idsToAdd])];

        if (idsToAdd.length < currentUnselectedIds.length) {
          this.$message.warning({
            message: `系统勾选上限为${this.SELECT_LIMIT}条，本次仅勾选${
              idsToAdd.length
            }条（剩余${remainingLimit - idsToAdd.length}条额度）`,
            duration: 5000,
          });
        }
      } else {
        const currentPageIds = this.searchResults.map((item) => item.id);
        this.selectedIds = this.selectedIds.filter(
          (id) => !currentPageIds.includes(id)
        );
      }
    },

    handleClearSelection() {
      this.selectedIds = [];
    },

    handleSelectItem(checked, id) {
      if (checked && this.selectedIds.length >= this.SELECT_LIMIT) {
        this.$message.warning(`系统勾选上限为${this.SELECT_LIMIT}条，已达上限`);
        return;
      }

      if (checked) {
        if (!this.selectedIds.includes(id)) {
          this.selectedIds.push(id);
        }
      } else {
        this.selectedIds = this.selectedIds.filter(
          (itemId) => itemId !== id
        );
      }
    },

    // 排序控制
    handleSort(type) {
      if (this.sortType === type) {
        this.sortOrder = this.sortOrder === "asc" ? "desc" : "asc";
      } else {
        this.sortType = type;
        this.sortOrder = "desc";
      }
      this.fetchData();
    },

    // 功能操作
    handleDownload() {
      if (this.selectedCount === 0) {
        this.$message.warning("请先选择要下载的内容");
        return;
      }
      this.$message.success(`已开始下载选中的${this.selectedCount}条内容`);
    },

    handleExport() {
      if (this.selectedCount === 0) {
        this.$message.warning("请先选择要导出的内容");
        return;
      }
      this.$refs.exportDialog.openExportDialog();
      this.$message.success(`已开始导出选中的${this.selectedCount}条内容`);
    },

    handleStatistic() {
      this.$router.push({
        name: "StatisticalAnalysis",
        query: "",
      });
    },

    handleTranslate() {
      if (this.selectedCount === 0) {
        this.$message.warning("请先选择要翻译的内容");
        return;
      }
      this.$message.success(`已开始翻译选中的${this.selectedCount}条内容`);
    },

    // 结果中搜索
    handleSearchInResult() {
      if (!this.searchInResultKeyword.trim()) {
        this.$message.warning("请输入搜索关键词");
        return;
      }
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },
  },
  created() {
    this.fetchData();
  },
  mounted() {
    const container = document.querySelector(".home");
    if (container) {
      container.addEventListener("scroll", this.handleScroll);
    }
  },
  beforeDestroy() {
    const container = document.querySelector(".home");
    if (container) {
      container.removeEventListener("scroll", this.handleScroll);
    }
  },
};
</script>

<style lang="scss" scoped>
.pagination {
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-pager li {
  background-color: #f9faff;
}

::v-deep .el-pagination .btn-next,
.el-pagination .btn-prev {
  background-color: #f9faff;
}

::v-deep .el-pagination .btn-prev {
  background-color: #f9faff;
}

// 基础样式
.search-result-area {
  width: 1060px;
  background: #ffffff;
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.07);
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-info {
  width: 1060px;

  .search-header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 19px;

    .search-result-count {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 18px;
      color: #333333;

      .count-number {
        color: #e51d28;
        padding: 0 7px;
      }
    }

    .search-controls {
      display: flex;

      .pagination-controls {
        display: flex;
        align-items: center;
        font-size: 18px;
        color: #333;

        .page-info {
          padding: 0 17px;
        }

        i {
          cursor: pointer;

          &.disabled {
            cursor: not-allowed;
            color: #ccc;
          }
        }
      }

      .view-controls {
        display: flex;
        align-items: center;
        height: 28px;
        background: #fff;
        border-radius: 2px;
        border: 1px solid #e4e4e4;
        margin-left: 16px;

        .chanpinliebiaopubuliumoshi,
        .fenye {
          cursor: pointer;
          width: 36px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;

          &.active {
            color: #327dff;
          }
        }

        .fenye {
          border-right: 1px solid #e4e4e4;

          i {
            font-size: 16px;
          }
        }

        .chanpinliebiaopubuliumoshi {
          i {
            font-size: 19px;
          }
        }
      }
    }
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e4e4;

    .left-operations {
      display: flex;
      align-items: center;

      .selected-checkbox {
        margin-right: 20px;

        ::v-deep .el-checkbox__label {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 18px;
          color: #333333;
        }
      }

      .selected-count {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 18px;
        color: #333333;
        margin-right: 20px;

        span {
          font-size: 18px;
          color: #327dff;
        }
      }

      .qing {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 18px;
        color: #333333;
        margin-right: 20px;

        &:hover {
          color: #327dff;
        }
      }
    }

    .right-operations {
      display: flex;
      align-items: center;
      gap: 24px;

      div {
        cursor: pointer;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 18px;
        color: #333333;
        display: flex;
        align-items: center;
        gap: 4px;

        &:hover {
          color: #327dff;
        }

        i {
          font-size: 18px;
        }

        &.active i {
          color: #327dff;
        }
      }

      .button1 {
        width: 73px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #327dff;
        border-radius: 4px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 18px;
        color: #ffffff !important;

        i {
          font-size: 18px;
          margin-right: 4px;
        }
      }
    }
  }

  .search-in-result {
    display: flex;
    height: 95px;
    align-items: center;
    padding: 0 20px;

    &__label {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      margin-right: 12px;
    }

    &__input {
      width: 320px;
      margin-right: 16px;
    }

    &__button {
      width: 72px;
      border-radius: 4px;
    }
  }
}

.Detail {
  padding-top: 24px;
  padding-bottom: 40px;
  display: flex;
  background: #f9faff;
  flex-direction: column;
  align-items: center;

  .mixin {
    width: 1400px;
    display: flex;
  }

  .left {
    margin-right: 20px;
  }

  .right {
    width: 1060px;
  }
}

// 结果列表样式
.result-list-container {
  width: 1060px;
}

// 瀑布流视图样式
.card-view {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 20px;
}

.result-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  }

  .card-checkbox {
    margin-bottom: 12px;
  }

  .card-content {
    .card-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 8px;
      cursor: pointer;

      &:hover {
        color: #327dff;
      }
    }

    .card-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: #999;
    }
  }
}

// 加载状态样式
.loading-tip, .no-more-tip {
  text-align: center;
  padding: 20px 0;
  color: #666;
  font-size: 14px;
}

.no-more-tip {
  color: #999;
}

// 空状态样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160px 0;
  color: #999;

  .aa {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #666666;

    .empty-text {
      margin-top: 18px;
    }
  }
}
</style>
